package com.qcq.wecheck.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;

import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * <p>
 * oss云存储中心 工具类
 * 不允许外界new
 * </p>
 *
 * @author O
 * @version 1.0
 * @since 2018/9/21
 */
public class OssUtils {
	private OssUtils() {
	}

	private static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";
	private static final String ACCESS_KEY = "LTAI1FmRmemSTkn3";
	private static final String ACCESS_KEY_SECRET = "gL3UdgCuLx4JIEamQHzajrFkBM7XyY";
	private static final String BACKGROUND_IMAGE_KEY_PREFIX = "background/schedule/";
	private static final String BUCKET_NAME = "wecheck";
	private static final String URL_PREFIX = "https://wecheck.oss-cn-beijing.aliyuncs.com/";

	private static final Random RANDOM = new Random(0);

	public volatile static List<String> BACKGROUND_IMAGE_URLS = getAllUrl();

	/**
	 * 随机获取一个图片url
	 * 图片基数要足够大,否则容易取到相同的
	 */
	public static String getRandomUrl() {
		List<String> urls = BACKGROUND_IMAGE_URLS;
		return urls.get(RANDOM.nextInt(urls.size()));
	}

	/**
	 * 获取oss上所有图片
	 */
	public static List<String> getAllUrl() {
		OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY, ACCESS_KEY_SECRET);
		ObjectListing objectListing = ossClient.listObjects(BUCKET_NAME, BACKGROUND_IMAGE_KEY_PREFIX);
		List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
		//删除第一个(目录)
		sums.remove(0);
		ossClient.shutdown();
		return sums
				.stream()
				.map(object -> URL_PREFIX + object.getKey())
				.collect(Collectors.toList());
	}

}
